package com.loyal.mwm.base;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.loyal.core.adapter.BaseListAdapter;

import java.util.List;

public abstract class BaseBindAdapter<T, VB extends ViewDataBinding> extends BaseListAdapter<T, BaseBindAdapter.ListBindViewHolder<VB>> {
    protected VB binding;

    public BaseBindAdapter() {
        super();
    }

    public BaseBindAdapter(List<T> arrList) {
        super(arrList);
    }

    public abstract int variableId();

    @Override
    public ListBindViewHolder<VB> createViewHolder(View view) {
        return new ListBindViewHolder<VB>(view);
    }

    @Override
    public void onViewHolder(@NonNull ListBindViewHolder<VB> holder, int position) {
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            //创建一个dataBinding
            binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), adapterLayout(), parent, false);
            //获取convertView
            convertView = binding.getRoot();
        } else {
            //去除convertView中banding的dataBinding
            binding = DataBindingUtil.getBinding(convertView);
        }
        T t = getItem(position);
        binding.setVariable(variableId(), t);
        return convertView;
    }

    public static class ListBindViewHolder<VB extends ViewDataBinding> extends BaseListAdapter.ViewHolder {
        private final VB binding;

        public ListBindViewHolder(@NonNull View itemView) {
            super(itemView);
            binding = DataBindingUtil.bind(itemView);
        }

        public VB getBinding() {
            return binding;
        }
    }

}
